package com.bill.concurrency.times;


import com.bill.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * SimpleDateFormat是线程不安全的。
 * @author bill
 */
@Slf4j
public class DateFormatExample2 {
    private static int clientTotal=5000;
    private static int threadTotal=200;



    public static void main(String[] args) {
        final ExecutorService executorService=Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch=new CountDownLatch(clientTotal);
        final Semaphore semaphore=new Semaphore(threadTotal);
        for(int i=0;i<clientTotal;i++){
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    formatDate();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("error:{}",e);
                }
                countDownLatch.countDown();
            });
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("error:{}",e);
        }

        log.info("5000次调用全部完成");

    }

    private static void formatDate(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyMMdd");
        try {
            sdf.parse("20180507");
        } catch (ParseException e) {
            log.error("发生错误:{}",e);
        }
    }
}
